package com.tjh4.exer;

import com.tjh2.util.JDBCUtils;
import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Scanner;

/**
 * @ClassName Exer1Test
 * @Description ：
 * @Author tang'jia'hao
 * @Date 2021/9/16 18:51
 * @Version 1.0
 **/
public class Exer1Test {
//    @Test
//    public void testInsert() {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        System.out.print("输入用户名：");
        String name = scanner.next();
        System.out.print("输入邮箱：");
        String email = scanner.next();
        System.out.print("输入生日：");
        String birthday = scanner.next(); // 隐式转换 "1992-09-08"

        String sql = "insert into customers(name,email,birth)values(?,?,?)";
        int insertCount = update(sql, name, email, birthday);
        if(insertCount > 0){
            System.out.println("添加成功");
        }else{
            System.out.println("添加失败");
        }

    }

    // 通用的增删改操作
    public static int update(String sql, Object ...args) {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            // 连接
            conn = JDBCUtils.getConnection();
            // 预编译
            ps = conn.prepareStatement(sql);
            // 填充占位符
            for(int i = 0; i < args.length; i++){
                ps.setObject(i+1, args[i]);
            }
            // 执行
            // ps.execute();
            return ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(conn, ps);
        }
        return 0;
    }
}
